package cn.net.springboot.netty.learn.custom;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class NettyLuckServer {

    // 指定端口号
    private static final int PORT = 8888;

    public static void main(String[] args) throws InterruptedException {

        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            // 指定socket的一些属性
            serverBootstrap.option(ChannelOption.SO_BACKLOG, 1024);
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)  // 指定是一个NIO连接通道
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new NettyLuckServerInitializer());

            // 绑定对应的端口号,并启动开始监听端口上的连接
            Channel ch = serverBootstrap.bind(PORT).sync().channel();

            System.out.printf("luck协议启动地址：127.0.0.1:%d/\n", PORT);

            // 等待关闭,同步端口
            ch.closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    static class NettyLuckServerInitializer extends ChannelInitializer<SocketChannel> {

        @Override
        protected void initChannel(SocketChannel channel) throws Exception {
            // 添加编解码器, 由于ByteToMessageDecoder的子类无法使用@Sharable注解,
            // 这里必须给每个Handler都添加一个独立的Decoder.
            channel.pipeline().addLast(new LuckEncoder());
            channel.pipeline().addLast(new LuckDecoder());

            // 添加逻辑控制层
            channel.pipeline().addLast(new NettyLuckServerHandler());

        }
    }

    static class NettyLuckServerHandler extends SimpleChannelInboundHandler<LuckMessage> {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, LuckMessage msg) throws Exception {
            // 简单地打印出server接收到的消息
            System.out.println(msg.toString());
        }
    }
}